"""
    权限校验基类
"""
import jwt
import json
from django.views import View
from user.models import UserProfile
from django.conf import settings
from django.http import JsonResponse


class BaseView(View):
    def dispatch(self, request, *args, **kwargs):
        # 1.获取token
        #   DJANGO会把请求头大写,并加上HTTP_
        token = request.META.get("HTTP_AUTHORIZATION")
        if not token:
            return JsonResponse({"code": 403, "error": "Please login01"})

        # 2.校验token[jwt模块 decode()]
        try:
            # payload: {"exp": xx, "username": "zhaoliying"}
            payload = jwt.decode(token, key=settings.JWT_TOKEN_KEY, algorithms="HS256")
        except Exception as e:
            return JsonResponse({"code": 403, "error": "Please login02"})

        #
        username = payload.get("username")
        try:
            user = UserProfile.objects.get(username=username)
        except:
            return JsonResponse({"code": 403, "error": "Please login03"})

        # 给所有套过装饰器的方法的request参数,都增加了一个myuser属性
        request.myuser = user

        data_loads = None
        if request.body:
            data_loads = json.loads(request.body)

        request.data = data_loads

        return super().dispatch(request, *args, **kwargs)













